﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Lbb.DataAnnotations;
using Lbb.URating.Localization;
using Lbb.Security;

namespace Lbb.URating.DL
{
    [MetadataType(typeof(_U_ClickCategory))]
    public partial class U_ClickCategory
    {
        #region Fields
        /// <summary>
        /// 综合评分缓存
        /// </summary>
        private Dictionary<string, decimal> overallRatingCache = new Dictionary<string, decimal>();
        #endregion Fields

        #region Props
        /// <summary>
        /// 点击器集哈希码
        /// </summary>
        public string ClicksHash
        {
            get
            {
                return _clicksHash ?? (_clicksHash = Cryptography.MD5(U_Click.OrderBy(d => d.Ordering).Select(d => d.ClickID).ToList().Select(d => d.ToString()).Aggregate((d, e) => d + e)));
            }
        }
        private string _clicksHash;
        #endregion Props

        #region Methods
        /// <summary>
        /// 取得综合评分
        /// </summary>
        /// <param name="objId">关联对象ID</param>
        /// <param name="useCache">使用缓存值</param>
        public decimal GetOverallRating(string objId, bool useCache = true)
        {
            if (string.IsNullOrEmpty(objId)) throw new ArgumentNullException("objId");
            var hasValue = useCache && overallRatingCache.ContainsKey(objId);

            if (hasValue) return overallRatingCache[objId];

            var ratings = U_Click.Where(d => d.IsRating).SelectMany(d => d.U_ClickRating).Where(d => d.ObjectID == objId);
            var overallRating = ratings.Count() < 1 ? 0 : ratings.Average(d => d.AverageRating);
            overallRatingCache[objId] = overallRating;

            return overallRating;
        }
        #endregion Methods
    }
    internal class _U_ClickCategory
    {
        [Display(ResourceType = typeof(U_ClickCategoryRes), Name = "Title")]
        [NRequired]
        [NStringLength(256)]
        public string Title { get; set; }

        [Display(ResourceType = typeof(U_ClickCategoryRes), Name = "ObjectType")]
        [NStringLength(256)]
        public string ObjectType { get; set; }

        [Display(ResourceType = typeof(U_ClickCategoryRes), Name = "AllowRedo")]
        public bool AllowRedo { get; set; }
    }
}
